package cn.dreamarts;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.dbconnection.DBConnection;
import cn.dbconnection.MD5Crypt;

public class Login {
	private static String sql = "SELECT pass,mid FROM IS_MEMBER WHERE trim(user_id) = ?";
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;

	public Login() {
		conn = DBConnection.getConnection();
	}

	public boolean check_login(String user_id, String password) {
		String db_pass = null;
		if (user_id != null && password != null) {
			try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, user_id);
				rs = pstmt.executeQuery();
				if (rs.next()) {
					db_pass = rs.getString("pass").trim();
					String pass = MD5Crypt.crypt(password, db_pass.substring(3,
							5));
					if (pass.equals(db_pass)) {
						return true;
						// return createXMLFile(rs.getInt("mid"));
					}
				}
			} catch (SQLException sqle) {
				sqle.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	// private Document createXMLFile(int mid) throws IOException, JDOMException
	// {
	// System.out.println("in createXMLFile" + mid);
	// String name = null;
	// String kana = null;
	// String alpha = null;
	// String title = null;
	// String email = null;
	// String sql =
	// "SELECT name,kana,alpha,title,email FROM IS_MEMBER WHERE mid = ?";
	// try {
	// PreparedStatement pstmt = conn.prepareStatement(sql);
	// pstmt.setInt(1, mid);
	// ResultSet rs = pstmt.executeQuery();
	// name = rs.getString("name");
	// System.out.println(name);
	// kana = rs.getString("kana");
	// alpha = rs.getString("alpha");
	// title = rs.getString("title");
	// email = rs.getString("email");
	// } catch (SQLException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// Element root = new Element("root");
	// Document doc = new Document(root);
	// Element elements = new Element("user");
	// elements.addContent(new Element("name").setText(name));
	// elements.addContent(new Element("kana").setText(kana));
	// elements.addContent(new Element("alpha").setText(alpha));
	// elements.addContent(new Element("title").setText(title));
	// elements.addContent(new Element("email").setText(email));
	// root.addContent(elements);
	// XMLOutputter XMLOut = new XMLOutputter();
	// XMLOut.output(doc, new FileOutputStream(mid + ".xml"));
	// System.out.println(doc.toString());
	// return doc;
	// }
}
// http://xianzhideng.javaeye.com/blog/524297